﻿Imports System.Reflection
Imports Microsoft.Xna.Framework

Namespace Global.Runa.UI.Animation

    Public MustInherit Class AnimationBase

        Public Event Complete As EventHandler

        Protected _TargetPropertyName As String
        Protected Coefficient As Integer = 1
        Protected Progress As Single
        Protected ProgressIncremental As Single
        Protected TargetProperty As PropertyInfo

        Public Property Duration As TimeSpan
        Public Property TargetObject As IAnimatable
        Public Property EasingFunction As EasingFunctionBase
        Public Property IsEnabled As Boolean = False
        Public Property IsRepeat As Boolean
        Public Property IsFinished() As Boolean = False

        Public Property FPS() As Single = 60.0!

        Public Property TargetPropertyName As String
            Get
                Return Me._TargetPropertyName
            End Get
            Protected Set(ByVal value As String)
                Me._TargetPropertyName = value
            End Set
        End Property

        Public Sub New()
            Me.FPS = 60.0!
        End Sub

        Public Sub New(ByVal fps As Single)
            Me.FPS = fps
        End Sub

        Public Overridable Sub BeginAnimation(ByVal TargetObject As IAnimatable, ByVal TargetPropertyName As String)
            Me.TargetObject = TargetObject
            Me.TargetPropertyName = TargetPropertyName
#If NETFX_CORE Then
            Me.TargetProperty = TargetObject.GetType.GetRuntimeProperties(TargetPropertyName)
#Else
            Me.TargetProperty = TargetObject.GetType.GetProperty(TargetPropertyName)
#End If
            If (Me.TargetProperty Is Nothing) Then
                Throw New Exception("Property not found.")
            End If
            Me.ProgressIncremental = Me.CalculateProgressIncremental(Me.Duration)
            Me.IsEnabled = True
            Me.Progress = 0.0!
            TargetObject.Animations.Add(Me)
        End Sub

        Private Function CalculateProgressIncremental(ByVal Time As TimeSpan) As Single
            Return 1.0! / CSng(Time.TotalSeconds * 60)
        End Function

        Public Overridable Sub OnComplete()
            Me.IsEnabled = False
            Me.IsFinished = True
            RaiseEvent Complete(Me, Nothing)
        End Sub

        Public Overridable Sub Updata(ByVal gameTime As GameTime)
            If Me.IsRepeat Then
                If Me.Progress > 1.0! Or Me.Progress < 0.0! Then
                    Me.Coefficient = -Me.Coefficient
                End If
                Me.Progress += Me.ProgressIncremental * Me.Coefficient
            Else
                If Me.Progress >= 1.0! Then
                    Me.OnComplete()
                End If
                Me.Progress += Me.ProgressIncremental * CSng(Me.Coefficient)
            End If
        End Sub

    End Class

End Namespace
